package cn.lm.activit.module;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author lm_jcf
 * @date 2019/2/22 10:28
 */
public class ZipUnzipHandle {

    private static final int  BUFFER_SIZE = 2 * 1024;

    public static void main(String[] args) {
        try {
            List<File> fileList = new ArrayList<>();
            fileList.add(new File("C:\\Users\\lm_jcf\\Desktop\\小鸟.png"));
            fileList.add(new File("C:\\Users\\lm_jcf\\Desktop\\-653915209.jpg"));
            FileOutputStream fos2 = new FileOutputStream(new File("C:\\Users\\lm_jcf\\Desktop\\mytest03.zip"));
            ZipUnzipHandle.toZip(fileList, fos2);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
//            zos = new ZipOutputStream(out, Charset.forName("utf-8"));
            zos = new ZipOutputStream(out, Charset.forName("GBK"));
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
